package com.dcsgo.myTankGameServers;

import com.dcsgo.myTankGameServers.common.Message;
import com.dcsgo.myTankGameServers.common.MessageType;
import com.dcsgo.myTankGameServers.common.PlayerTank;

import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Properties;

/**
 * @author DCSGO
 * @version 1.0
 * 监听并响应连接到的客户端
 */
public class ServerConnectThread extends Thread {
    private final Socket socket;
    private final int clientId;
    private static boolean loop = true;


    ServerConnectThread(int clientId, Socket clientSocket) {
        this.clientId = clientId;
        this.socket = clientSocket;
    }

    public int getClientId() {
        return clientId;
    }

    @Override
    public void run() {
        try {
            while (loop) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                Message message = (Message) ois.readObject();
                switch (message.getMesType()) {
                    case MessageType.MESSAGE_ONLINE:
                        System.out.println("玩家上线");
                        //生成一个坦克
                        TankManager.produceTank(clientId);
                        Message sendMes = new Message();
                        message.setMesType(MessageType.MESSAGE_NODES);
                        message.setReceiver(clientId);
                        message.setTanks(TankManager.getTanks());
                        oos.writeObject(message);
                        break;
                    case MessageType.MESSAGE_TANKS:
                        System.out.println("收到坦克信息");
                        break;
                    case MessageType.MESSAGE_CLIENT_EXIT:
                        System.out.println("客户端下线");
                        loop = false;
                        ClientSocketManage.remove(clientId);
                        break;
                    default:
                        System.out.println("有误的message！");
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
